package com.asm.service;

import com.asm.dto.PageResult;
import com.asm.entity.sys.SpotTag;
import com.asm.repository.SpotTagRepository;
import com.asm.util.SnowflakeIdWorker;
import com.asm.vo.sys.SpotTagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ZhuangGuiMan
 */
@Service
public class SpotTagService {
    @Resource
    private SpotTagRepository spotTagRepository;
    @Resource
    private SnowflakeIdWorker snowflakeIdWorker;

    /**
     * 获取广告位标签列表
     *
     * @param page 分页对象
     * @return 广告位标签列表
     */
    private List<SpotTagVo> getSpotTagVoList(Page<SpotTag> page) {
        List<SpotTagVo> list = new ArrayList<>();
        for (SpotTag spotTag : page.getContent()) {
            SpotTagVo spotTagVo = new SpotTagVo();
            BeanUtils.copyProperties(spotTag, spotTagVo);
            list.add(spotTagVo);
        }
        return list;
    }

    /**
     * 添加广告位标签
     *
     * @param spotTagVo 广告位标签
     */
    @Transactional(rollbackFor = Exception.class)
    public void addSpotTag(SpotTagVo spotTagVo) {
        SpotTag spotTag = new SpotTag();
        BeanUtils.copyProperties(spotTagVo, spotTag);
        spotTag.setId(snowflakeIdWorker.nextId());
        spotTag.setCreateBy(1L);
        spotTag.setCreateAt(new Date());
        spotTag.setUpdateBy(1L);
        spotTag.setUpdateAt(new Date());
        spotTagRepository.save(spotTag);
    }

    /**
     * 删除广告位标签
     *
     * @param id 广告位标签编号
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteSpotTag(Long id) {
        spotTagRepository.deleteById(id);
    }

    /**
     * 分页查询所有广告位标签
     *
     * @param pageNumber 当前页码
     * @param pageSize   页面大小
     * @return 分页形式的广告位标签列表
     */
    public PageResult<SpotTagVo> findAllSpots(Integer pageNumber, Integer pageSize) {
        Page<SpotTag> page = spotTagRepository.findAll(PageRequest.of(pageNumber, pageSize));
        return new PageResult<>(pageNumber, pageSize, page.getTotalPages(), getSpotTagVoList(page));
    }

    /**
     * 更新广告位标签
     *
     * @param spotTagVo 广告位标签
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSpot(SpotTagVo spotTagVo) {
        SpotTag spotTag = spotTagRepository.findById(spotTagVo.getId()).get();
        BeanUtils.copyProperties(spotTagVo, spotTag);
        spotTag.setUpdateBy(1L);
        spotTag.setUpdateAt(new Date());
        spotTagRepository.save(spotTag);
    }
}
